package com.lh.jianzhioffer.专项练习.链表;

/**
 * @author: linghao
 * @since: 2023/3/6
 *
 * 给定一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点
 */
public class 删除链表的倒数第n个结点021 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
//        ListNode node2 = new ListNode(2);
//        ListNode node3 = new ListNode(3);
//        ListNode node4 = new ListNode(4);
//        ListNode node5 = new ListNode(5);
//        node1.next = node2;
//        node2.next = node3;
//        node3.next = node4;
//        node4.next = node5;
        removeNthFromEnd(node1,1);
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        int len = 0;
        ListNode temp = head;
        while (temp != null){
            temp = temp.next;
            len++;
        }
        //让head走到被删除节点的头一个节点的位置
        ListNode cur = dummy;
        for(int i=1;i<len-n+1;i++){
            cur = cur.next;
        }
        cur.next = cur.next.next;
        return dummy.next;

    }



    public static class ListNode {
         int val;
         ListNode next;
         ListNode() {}
         ListNode(int val) { this.val = val; }
         ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     }
}
